﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DNA.OpenAPI.Atom;
using DNA.OpenAPI.Rss;

namespace DNA.OpenAPI.OpenSearch
{
    public abstract class OpenSearchProvider : IOpenSearchProvider
    {
        public virtual string Name { get; set; }

        public abstract string Title { get; }

        public virtual bool SupportSuggestion { get { return false; } }

        public abstract IEnumerable<AtomEntry> GetAtomResult(string searchTerms, int pageIndex, int pageSize, out int totalRecords);

        public abstract IEnumerable<RssItem> GetRssResult(string searchTerms, int pageIndex, int pageSize, out int totalRecords);

        public virtual IEnumerable<OpenSearchSuggestion> Suggest(string searchTerms, int count) 
        {
            return null;
        }

        IEnumerable<OpenSearchSuggestion> IOpenSearchProvider.Suggest(string searchTerms, int count)
        {
            return this.Suggest(searchTerms,count);
        }

        void IOpenSearchProvider.Search(ref OpenSearchQuery query, out OpenSearchAtomResult result)
        {
            var pageSize = query.Count > 0 ? query.Count : 20;
            int total = 0;
            var resultSet = GetAtomResult(query.SearchTerms, query.StartIndex, pageSize, out total);

            query.TotalResults = total;

            var feed = new OpenSearchAtomResult()
            {
                Entries = resultSet.ToList(),
                TotalResults = total,
                Query = query,
                StartIndex = query.StartIndex,
                ItemsPerPage = pageSize,
                Title = query.Title
            };
            result = feed;
        }

        void IOpenSearchProvider.Search(ref OpenSearchQuery query, out OpenSearchRssResult result)
        {
            var pageSize = query.Count > 0 ? query.Count : 20;
            int total = 0;
            var resultSet = GetRssResult(query.SearchTerms, query.StartIndex, pageSize, out total);
            query.TotalResults = total;

            var feed = new OpenSearchRssResult()
            {
                Items = resultSet.ToList(),
                Query = query,
                Title = query.Title
            };
            result = feed;
        }
    }
}
